package com.sduept.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ListUtils {
	/**
	 * 根据序号排序
	 * @param originList  原来的list
	 * @param oldOrderNo  被修改对象的原来位置
	 * @param newOrderNo  被修改对象的新位置
	 * @param sortFieldName  被修改对象的属性名
	 * @return changedList已被修改顺序的list,需要重新update到数据库
	 */
	public static <T> List<T> sortListByOrderNo(List<T> originList,int oldOrderNo,int newOrderNo,final String sortFieldName){
		List<T> changedList=new ArrayList<T>();
		if(originList.size()>0&&newOrderNo>=0 &&oldOrderNo>=0){
			PropertyDescriptor pd=null;
			T selected=	originList.get(oldOrderNo);
			Method setMethod=null;
			try {
				pd=new PropertyDescriptor(sortFieldName,selected.getClass());
				if(pd!=null){
					setMethod=pd.getWriteMethod();
				}
				originList.remove(oldOrderNo);
				originList.add(newOrderNo, selected);
				int beginIndex=0;
				int endIndex=0;
				if(oldOrderNo>newOrderNo){
					//往前移动
					beginIndex=newOrderNo;
					endIndex=oldOrderNo;
				}else{
					//往后移动
					beginIndex=oldOrderNo;
					endIndex=newOrderNo;
				}
				for(int i=beginIndex;i<=endIndex;i++){
					setMethod.invoke(originList.get(i), i);
					changedList.add(originList.get(i));
				}
			} catch (Exception e) {
				e.printStackTrace();
				return changedList;
			}
		}
		return changedList;
	}
}
